<template>
  <view class="taskListUpdatePage">
    <view class="content">
      <uni-forms :ref="taskListAddForm" :rules="rules" :modelValue="form" label-position="top">
        <uni-forms-item label="标题" required name="title">
          <uni-easyinput v-model="form.title" placeholder="请输入标题"/>
        </uni-forms-item>
        <uni-forms-item label="描述" name="description">
          <uni-easyinput type="textarea" v-model=" form.description" placeholder="请输入描述"/>
        </uni-forms-item>
        <uni-forms-item label="标签" name="tags">
          <text>{{JSON.stringify(tempTags)}}</text>
        </uni-forms-item>
        <uni-forms-item label="输入标签">
          <view class="form-tags-item">
            <uni-easyinput v-model="tempTag" placeholder="请输入标签" />
            <button class="button" size="mini" type="default" @click="handleInputTags">添加</button>
          </view>
        </uni-forms-item>
        <uni-forms-item label="所需时间" required name="age">
          <uni-easyinput type="number" v-model="form.needTime" placeholder="请输入所需时间"/>
        </uni-forms-item>
        <uni-forms-item label="类型">
          <uni-data-checkbox v-model="form.taskType" :localdata="taskType"/>
        </uni-forms-item>
        <uni-forms-item label="频率">
          <uni-data-checkbox v-model="form.frequency" :localdata="frequency"/>
        </uni-forms-item>
        <uni-forms-item label="开始时间">
          <uni-datetime-picker @change="()=> isStartTimeUpdate = true" type="datetime" return-type="timestamp"
                               v-model="form.startDate"/>
        </uni-forms-item>
        <uni-forms-item label="结束时间">
          <uni-datetime-picker @change="()=> isEndTimeUpdate = true" type="datetime" return-type="timestamp"
                               v-model="form.endDate"/>
        </uni-forms-item>
      </uni-forms>
    </view>
    <view class="footer">
      <button class="btnCls" @click="handleBack">返回</button>
      <button class="btnCls" @click="handleSubmit">提交</button>
    </view>
  </view>
</template>
<script setup lang="ts">
import {ref, watch} from 'vue'
import {
  getTaskListByIdUsingGet,
  updateTaskListUsingPost
} from "@/services/api/taskListController";
import {onLoad} from "@dcloudio/uni-app";

const form = ref<API.TaskListUpdateRequest>({})
const taskListAddForm = ref('taskListAddForm');
const taskListId = ref(0)
const isStartTimeUpdate = ref(false);
const isEndTimeUpdate = ref(false);

const tempTag = ref<string>("");
const tempTags = ref<string[]>([]);

const rules = {
  title: {
    rules: [{
      required: true,
      errorMessage: '标题不能为空'
    }]
  },
}

const taskType = [
  {
    text: '单次',
    value: 'ONCE'
  },
  {
    text: '周期',
    value: 'CYCLE'
  }
]

const frequency = [
  {
    text: '日',
    value: 'DAILY'
  },
  {
    text: '周',
    value: 'WEEKLY'
  },
  {
    text: '月',
    value: 'MONTHLY'
  }
]
const handleBack = () => {
  uni.switchTab({
    url: '/pages/home/index'
  });
}


/**
 * 加载数据
 */
const loadTaskListData = async () => {
  uni.showLoading({
    title: '加载中'
  });
  const data = await getTaskListByIdUsingGet({id: taskListId.value}) as API.TaskList;
  if(data) {
    form.value = data as API.TaskListUpdateRequest;
    if (form.value.tags) {
      // @ts-ignore
      tempTags.value = JSON.parse(form.value.tags)
    }
  }
  uni.hideLoading();
}

/**
 * 表单校验
 */
const formValidate = () => {
  try {
    const offset = 8 * 60 * 60 * 1000; // 东八区的时区偏移量（8小时）
    form.value.tags = tempTags.value ?? tempTags.value;

    if (isStartTimeUpdate.value) {
      // @ts-ignore
      const data = new Date(form.value.startDate + offset);
      form.value.startDate = data.toISOString();
    }
    if (isEndTimeUpdate.value) {
      // @ts-ignore
      const data = new Date(form.value.endDate + offset)
      form.value.endDate = data.toISOString();
    }
    if (!form.value.title) {
      uni.showToast({
        icon: 'error',
        title: '请输入标题'
      })
      return false;
    }
    return true;
  } catch (e) {
    uni.showToast({
      icon: 'error',
      title: '表单校验失败'
    })
  }
  return false;
}

const handleSubmit = async () => {
  try {
    if (formValidate()) {
      const data = await updateTaskListUsingPost({...form.value})
      if (data) {
        uni.showToast({
          icon: 'success',
          title: '修改成功'
        })
        handleBack();
      } else {
        uni.showToast({
          icon: 'error',
          title: '添加失败'
        })
      }
    }
  } catch (e) {
    uni.showToast({
      icon: 'error',
      title: '失败,稍后再试' + e
    })
  }
}

/**
 * 添加标签
 */
const handleInputTags = () => {
  if(tempTag.value) {
    if (tempTags.value) {
      console.log(typeof tempTags.value)
      tempTags.value.push(tempTag.value);
    } else {
      tempTags.value = new Array(tempTag.value);
    }
    tempTag.value = "";
  }
}

/**
 * ID改变重新加载数据
 */
watch(taskListId, () => {
  loadTaskListData();
})

onLoad((options: any) => {
  taskListId.value = options.id
})


</script>

<style scoped>
.taskListUpdatePage {
  height: 100vh;

  .content {
    padding: 5px;
  }

  .footer {
    display: flex;
    justify-content: space-between; /* 按钮之间的间距 */
    align-items: center; /* 垂直居中 */
    padding-bottom: 5vh;
  }

  .btnCls {
    width: 30vw;
    background: linear-gradient(to bottom, #ebf1fd, #ffffff); /* 渐变背景 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影 */
    transition: all 0.2s ease; /* 悬浮过渡效果 */
  }

  .btnCls:hover {
    transform: translateY(-2px); /* 悬浮时上移 */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 悬浮时阴影加深 */
  }
  .form-tags-item{
    .button {
      margin: 5px;
      float: right;
    }
  }
}

</style>
